import { defineComponent } from 'vue'
import { NButton, useDialog, useMessage } from 'naive-ui'
import modeler from '@/store/modeler'
import { useI18n } from 'vue-i18n'
import { processApi } from '@/api/modules/process'

const Deploys = defineComponent({
  name: 'Deploys',
  setup() {
    const { t } = useI18n()
    const modelerStore = modeler()

    const dialog = useDialog()
    const message = useMessage()

    const deployXml = async () => {
      try {
        const modeler = modelerStore.getModeler!

        if (!modeler) {
          return window.__messageBox.warning('模型加载失败，请刷新重试')
        }

        let version = 0
        const hisVersion = await processApi.findVersionList(modelerStore.getActiveId as string)
        if (hisVersion && hisVersion.success) {
          if (hisVersion.data && hisVersion.data.length > 0) {
            version = hisVersion.data[0].version
          }
        } else {
          console.error(hisVersion.message)
          return
        }
        const nextVer = version + 1

        const { xml } = await modeler.saveXML({ format: true, preamble: true })
        const params = {
          key: modelerStore.getActiveId as string,
          name: modelerStore.getActive!.businessObject.name,
          xml: xml as string,
          nextVer: `V${nextVer}`
        }
        const flowName = '流程【' + params.name + '(' + params.key + ')@' + params.nextVer + '】'
        dialog.info({
          title: `正在部署${flowName}`,
          showIcon: false,
          content: () => {
            return nextVer == 1 ? (
              <div style={{ marginTop: '15px' }}>你确定部署该流程吗？</div>
            ) : (
              <div style={{ marginTop: '15px' }}>
                每次流程部署将会产生一个新的流程版本, 后续发起的新流程将按最新版本运行,
                <br />
                在途及历史流程实例不受影响,
                <br />
                你确定部署新版本该流程吗？
              </div>
            )
          },
          positiveText: '确定',
          negativeText: '取消',
          onPositiveClick: () => {
            processApi.deployByXml(params).then((resp: any) => {
              if (resp.success) {
                message.success(`${flowName}已部署`)
                //shilei 通知父窗口 2023-10-05
                if (window.top) {
                  window.top.postMessage({ deploy: true }, import.meta.env.VITE_PARENT_DOMAIN)
                }
              }
            })
          }
        })
      } catch (e) {
        window.__messageBox.error((e as Error).message || (e as string))
      }
    }

    return () => (
      <NButton type="info" secondary onClick={deployXml}>
        {t('toolbar.deployByXml')}
      </NButton>
    )
  }
})

export default Deploys
